#!/usr/bin/env python
# -*- coding:utf-8 -*-

from mhook.frame.fridaframe import fhook
from madb.tools.printer import info,plus,warn
import base64

f_51testingPoc = """
Java.perform(function () {
  var MainActivity = Java.use('owasp.sat.agoat.TrafficActivity');
  var Toast = Java.use('android.widget.Toast');
  var context = Java.use('android.app.ActivityThread').currentApplication().getApplicationContext();
  MainActivity.onCreate.overload('android.os.Bundle').implementation = function (c) {
	    this.onCreate(c);
        console.log("劫持成功! by 51testingTeach");
        Toast.makeText(Java.use("android.app.ActivityThread").currentApplication().getApplicationContext(), 
        Java.use("java.lang.String").$new("劫持成功! by 51testingTeach"), 1).show();
    };
});
"""


f_tappHookSumPoc = """
Java.perform( function (){
    var mactivity = Java.use("com.example.mytest.SecondActivity");
    mactivity.sumCalc.implementation = function (x,y){
        var result = this.sumCalc(5,5);
        return result;
    }
}
);
"""
f_tappHookOverLoadPoc = """
Java.perform( function (){
    var mactivity = Java.use("com.example.mytest.SecondActivity");
    var strClass = Java.use("java.lang.String");

    mactivity.samefunc.overload("int","int").implementation = function (x,y){
        var result = this.samefunc(88,68);
        console.log("劫持第一个samefunc函数成功!");
        return result;
    }

    mactivity.samefunc.overload("java.lang.String").implementation = function (x){
        var myStr = strClass.$new("我的Hook字符串!");
        var result = this.samefunc(myStr);
        console.log("劫持第二个samefunc函数成功!");
        Toast.makeText(Java.use("android.app.ActivityThread").currentApplication().getApplicationContext(), 
        result, 1).show();
        return result;
        
    }
}

)
"""
f_tappHookSecretPoc = """
Java.perform(
    function (){
        Java.choose("com.example.mytest.SecondActivity",{
            onMatch: function (instance){
                console.log("堆内存中找到实例: " + instance);
                console.log("调用secret函数: " + instance.secret());
            },
            onComplete: function (){

            }
        }
        );
    }
)

"""
f_tappRpcPoc = """
var arrs = [];
function hookSecretFunc(){
    Java.perform(
        function (){
            if(arrs.length == 0){
                Java.choose("com.example.mytest.SecondActivity",{
                    onMatch: function (instance){
                            arrs.push(instance);
                            console.log("堆内存中找到实例: " + instance);
                            console.log("调用secret函数: " + instance.secret());                        
                    },
                    onComplete: function (){

                    }
                }
                );

            }else{
                for(i = 0; i<arrs.length;i++){
                    console.log("已存在的实例调用secret函数: " + arrs[i].secret());
                }
            }
        }
    );
}

rpc.exports = {
    hooksecret:hookSecretFunc
}

"""
f_tappHookTextViewPoc = """
function hookTextViewFunc(){
Java.perform(
    function (){
        var tv_class = Java.use("android.widget.TextView");
        tv_class.setText.overload("java.lang.CharSequence").implementation = function (x){
            var send_str = x.toString();
            var recv_str;
            send(send_str);
            recv(
                function (json_data){
                    console.log("recv");
                    recv_str = json_data.fix_data;
                    console.log(recv_str);
                }
            ).wait();
            console.log("recv end!");
            var set_str = Java.use("java.lang.String").$new("成功Hook控件显示内容: "+ recv_str);
            return this.setText(set_str);
        }
    }
)
}
rpc.exports = {
    hooktextview:hookTextViewFunc
}
"""
fhook_poc = {
    "AndroGoat": f_51testingPoc,
    "myapp":{
        'sumcalc':f_tappHookSumPoc,
        'samefunc':f_tappHookOverLoadPoc,
        'secretfunc':f_tappHookSecretPoc,
        'secretrpc':f_tappRpcPoc,
        "textview":f_tappHookTextViewPoc
    }
}

def onmessage(message,data):
    if message['type'] == 'send':
        info(message['payload'])
    else:
        info(message)

def base64_decode(encodeStr):
    try:
        str_encoder = base64.b64decode(encodeStr).decode("utf-8")
        return str_encoder
    except Exception as e:
        print(e)
        return "解码错误!"
def base64_encode(coderStr):
    try:
        str_coder = base64.b64encode(coderStr.encode('utf-8'))
        return str_coder.decode('utf-8')
    except Exception as e:
        print(e)
        return "编码错误!"
def textview_message_handler(message,data):
    if message['type'] == "send":
        data = message['payload'].split(":")[1].strip()
        data = base64_decode(data)
        uname,pwd = data.split(":")
        info(uname)
        info(pwd)

        